package com.winner.crmsoftware.employee;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.winner.crmsoftware.location.GPSTracker;
import com.winner.crmsoftware.main.R;
import com.winner.srmsoftware.json.ServiceHandler;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

public class SaleLocationActivity extends Activity {

	private GoogleMap googleMap;

	private ProgressDialog pDialog;
	ArrayList<Employee> dataArrayList = new ArrayList<Employee>();
	private static String url = "http://103.28.37.16:8080/crm_software/get_all_employee.php";
	private static final String TAG_EMPLOYEE = "employees";
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "name";
	private static final String TAG_LATITUDE = "latitude";
	private static final String TAG_LONGITUDE = "longitude";
	public GPSTracker gps;
	public GetEmployeesLocation employeesLocation;
	JSONArray customerJsonArray = null;

	public static final int UPDATE_LOCATION = 1;
	public static final int COUNT_TIME = 2;
	public Thread delayThread;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case UPDATE_LOCATION:
				new GetEmployeesLocation().execute();
				break;

			default:
				break;
			}
		}

	};

	int mSeconds = 0;
	int count = 0;

	Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sale_location_management);

		gps = new GPSTracker(SaleLocationActivity.this);
		if (!gps.canGetLocation()) {
			gps.showSettingsAlert();
		}
		
		

		// delayThread = new Thread(new DelayTimeUpdate());
		// delayThread.start();

		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				
				if (count == 0) {
					new GetEmployeesLocation().execute();
					count ++;
				}

				if (mSeconds == 10) {
					new GetEmployeesLocation().execute();
					mSeconds = 0;
				}
				mHandler.postDelayed(this, 1000);
				mSeconds++;

			}
		}, 1000);

	}

	@Override
	protected void onResume() {
		super.onResume();
		initilizeMap();
	}

	@SuppressLint("NewApi")
	private void initilizeMap() {
		if (googleMap == null) {
			googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.sale_location)).getMap();

			// check if map is created successfully or not
			if (googleMap == null) {
				Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
			}
		}
	}

	public class DelayTimeUpdate implements Runnable {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				handler.sendEmptyMessage(UPDATE_LOCATION);
			}
		}
	}

	/**
	 * Async task class to get json by making HTTP call
	 * */
	private class GetEmployeesLocation extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Showing progress dialog
			
			if (!isFinishing()) {
				pDialog = new ProgressDialog(SaleLocationActivity.this);
				pDialog.setMessage("Loading location...");
				pDialog.setCancelable(false);
				pDialog.show();	
			}
		}

		@SuppressLint("DefaultLocale")
		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			dataArrayList.clear();

			ServiceHandler sh = new ServiceHandler();
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

			if (jsonStr != null) {
				try {
					JSONObject jsonObj = new JSONObject(jsonStr);

					// Getting JSON Array node
					customerJsonArray = jsonObj.getJSONArray(TAG_EMPLOYEE);

					Log.e("Json Length", customerJsonArray.length() + "");
					// looping through All Contacts
					for (int i = 0; i < customerJsonArray.length(); i++) {
						JSONObject c = customerJsonArray.getJSONObject(i);

						String latitude = c.getString(TAG_LATITUDE);
						String longitude = c.getString(TAG_LONGITUDE);
						String name = c.getString(TAG_NAME);
						String employee_id = c.getString(TAG_ID);

						Employee employee = new Employee(employee_id, name, Double.valueOf(latitude), Double.valueOf(longitude));

						// Phone node is JSON Object

						// adding contact to contact list
						dataArrayList.add(employee);
						Log.e("Data SIze", dataArrayList.size() + "");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}
			Log.e("Add custom: ", "" + dataArrayList.size());
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Dismiss the progress dialog
			if (pDialog.isShowing())
				pDialog.dismiss();
			/**
			 * Updating parsed JSON data into ListView
			 * */

			try {
				// Loading map
				initilizeMap();

				// Changing map type
				googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
				// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);

				// Showing / hiding your current location
				googleMap.setMyLocationEnabled(true);

				// Enable / Disable zooming controls
				googleMap.getUiSettings().setZoomControlsEnabled(false);

				// Enable / Disable my location button
				googleMap.getUiSettings().setMyLocationButtonEnabled(true);

				// Enable / Disable Compass icon
				googleMap.getUiSettings().setCompassEnabled(true);

				// Enable / Disable Rotate gesture
				googleMap.getUiSettings().setRotateGesturesEnabled(true);

				// Enable / Disable zooming functionality
				googleMap.getUiSettings().setZoomGesturesEnabled(true);

				// lets place some 10 random markers
				for (int i = 0; i < dataArrayList.size(); i++) {
					// random latitude and logitude

					Log.e("Makeer", "" + dataArrayList.size());

					// Adding a marker
					MarkerOptions marker = new MarkerOptions().position(
							new LatLng(dataArrayList.get(i).getLatitude(), dataArrayList.get(i).getLongitude()))
							.title(dataArrayList.get(i).getName());

					marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN));

					googleMap.addMarker(marker);

					// Move the camera to last position with a zoom level
					if (i == (dataArrayList.size() - 1)) {
						CameraPosition cameraPosition = new CameraPosition.Builder()
								.target(new LatLng(dataArrayList.get(i).getLatitude(), dataArrayList.get(i).getLongitude())).zoom(10).build();
						googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		

		if (pDialog != null) {
			if (pDialog.isShowing()) {
				pDialog.dismiss();
				pDialog = null;
			}
		}
		
		super.onDestroy();
	}

}
